package com.leetcode.May;

/**
 * @Description: 接雨水
 * @Author: Mr.Fxy
 * @CreateTime: 2024-05-14 08:35
 */
public class CatchRainWater {
    public static void main(String[] args) {
trap(new int[]{4,2,0,3,2,5});
    }
    public static int trap(int[] height) {
        int length = height.length;
        if (length<3){
            return 0;
        }
        int sum=0;
        int[] left=new int[length];
        int[] right=new int[length];
        left[0]=height[0];
        for (int i = 1; i < length; ++i) {
        left[i]=Math.max(left[i-1],height[i]);
        }
        right[length-1]=height[length-1];
        for (int i = length-2; i >= 0; --i) {
            right[i]=Math.max(right[i+1],height[i]);
        }
        for (int i = 0; i < length; i++) {
            sum+=Math.min(left[i],right[i])-height[i];
        }
        return sum;
    }
}
